package com.atwu.wl2022.service.impl;

import com.atwu.wl2022.entity.*;
import com.atwu.wl2022.mapper.CommentMapper;
import com.atwu.wl2022.service.ICommentService;
import com.atwu.wl2022.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * <p>
 * 这是comment评论表
 * </p>
 *
 * @author wule
 * @since 2022-06-12
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

	@Autowired
	CommentMapper commentMapper;

	@Autowired
	IUserService iUserService;

	/**
	 * 查询评论,将评论层级组装好
	 * @return 评论集合
	 * @param articleId 文章id
	 */
	@Override
	public List<Comment> listComment(Integer articleId) {
		//根据文章id并且按照创建时间顺序查询该文章下所有评论
		List<Comment> comments = commentMapper.selectList(new QueryWrapper<Comment>().eq("article_id", articleId).orderByDesc("create_time"));
		return tidyComments(comments);
	}

	/**
	 * 整理评论集合comments
	 * @param articleComments 文章集合
	 * @return 整理好的集合
	 */
	private List<Comment> tidyComments(List<Comment> articleComments){
		//根据所有用户的userId，设置其comment对象中的headImage，nickName
		for(Comment comment:articleComments ){
			User user = iUserService.getById(comment.getUserId());
			comment.setReviewerIdentity(user.getIdentity());
			comment.setHeadImage(user.getImage());
			comment.setNickName(user.getNickName());
		}

		//查询评论（不包括回复） 过滤得到祖宗id为空的评论
		List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId()==null).collect(Collectors.toList());
		//设置评论数据的子节点
		for (Comment origin:originList ){
			//过滤得到回复的祖宗id等于评论的id,即多层回复的集合
			List<Comment> comments = articleComments.stream().filter(comment -> origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
			comments.forEach(comment -> {
				//如果存在回复的父id，给回复设置其父评论的用户id和用户昵称，这样评论就有能@的人的用户id和昵称
				// v 相当于过滤得到的父评论对象
				Optional<Comment> pComment = articleComments.stream().filter(c1 -> c1.getId().equals(comment.getPid())).findFirst();
				pComment.ifPresent((v ->{
					//找到父级评论的用户昵称和用户Id，并设置当前的回复对象
					comment.setParentUserId(v.getUserId());
					comment.setParentNickName(v.getNickName());
				}));
			});
			Collections.reverse(comments);
			origin.setReplyComments(comments);
		}
		return originList;
	}


}





